<template>
  <div class="ai-chat-float" :class="{ 'chat-expanded': isChatOpen }">
    <!-- 聊天图标/按钮 -->
    <div class="chat-toggle" @click="toggleChat">
      <div class="chat-icon">
        <i class="el-icon-chat-dot-round" v-if="!isChatOpen"></i>
        <i class="el-icon-close" v-else></i>
      </div>
      <div class="chat-label" v-if="!isChatOpen">AI 问答</div>
    </div>
    
    <!-- 聊天窗口 -->
    <div class="chat-window" v-if="isChatOpen">
      <div class="chat-header">
        <h3>AI金融助手</h3>
        <span class="close-btn" @click="toggleChat">×</span>
      </div>
      
      <div class="chat-messages" ref="messagesRef">
        <template v-if="chatHistory.length === 0">
          <div class="welcome-message">
            <div class="welcome-icon">
              <svg viewBox="0 0 100 100" width="60" height="60" xmlns="http://www.w3.org/2000/svg">
                <!-- 机器人头部 - 使用渐变色 -->
                <defs>
                  <linearGradient id="robot-head-float" x1="0%" y1="0%" x2="100%" y2="100%">
                    <stop offset="0%" stop-color="#4facfe" />
                    <stop offset="100%" stop-color="#00f2fe" />
                  </linearGradient>
                  <radialGradient id="eye-shine-float" cx="35%" cy="35%" r="60%" fx="35%" fy="35%">
                    <stop offset="0%" stop-color="#ffffff" stop-opacity="0.9" />
                    <stop offset="100%" stop-color="#f0f0f0" stop-opacity="0.1" />
                  </radialGradient>
                </defs>
                
                <!-- 主体 -->
                <rect x="30" y="20" width="40" height="60" rx="10" ry="10" fill="url(#robot-head-float)" />
                
                <!-- 天线 -->
                <line x1="40" y1="20" x2="40" y2="10" stroke="#4facfe" stroke-width="2" />
                <circle cx="40" cy="10" r="3" fill="#00f2fe" />
                <line x1="60" y1="20" x2="60" y2="10" stroke="#4facfe" stroke-width="2" />
                <circle cx="60" cy="10" r="3" fill="#00f2fe" />
                
                <!-- 眼睛外圈 -->
                <circle cx="40" cy="40" r="7" fill="#ffffff" />
                <circle cx="60" cy="40" r="7" fill="#ffffff" />
                
                <!-- 眼睛内部 -->
                <circle cx="40" cy="40" r="3.5" fill="#0f172a" />
                <circle cx="60" cy="40" r="3.5" fill="#0f172a" />
                
                <!-- 眼睛高光 -->
                <circle cx="38.5" cy="38.5" r="1.5" fill="white" />
                <circle cx="58.5" cy="38.5" r="1.5" fill="white" />
                
                <!-- 嘴巴 -->
                <rect x="40" y="55" width="20" height="5" rx="2.5" ry="2.5" fill="#ffffff" />
                
                <!-- 耳朵/侧部装饰 -->
                <rect x="25" y="35" width="5" height="15" rx="2.5" ry="2.5" fill="url(#robot-head-float)" />
                <rect x="70" y="35" width="5" height="15" rx="2.5" ry="2.5" fill="url(#robot-head-float)" />
                
                <!-- 胸部指示灯 -->
                <circle cx="50" cy="70" r="3" fill="#ffffff">
                  <animate attributeName="opacity" values="0.5;1;0.5" dur="2s" repeatCount="indefinite" />
                </circle>
              </svg>
            </div>
            <h4>您好！我是您的AI金融助手</h4>
            <p>我可以回答有关金融知识、投资策略、市场分析等问题。</p>
          </div>
        </template>
        
        <template v-else>
          <div 
            v-for="(msg, index) in chatHistory" 
            :key="index" 
            :class="['message', msg.role === 'user' ? 'user-message' : 'assistant-message']"
          >
            <div class="message-avatar">              <span v-if="msg.role === 'user'">👤</span>
              <span v-else>
                <svg viewBox="0 0 100 100" width="25" height="25" xmlns="http://www.w3.org/2000/svg">
                  <!-- 机器人头部 -->
                  <defs>
                    <linearGradient id="robot-chat-float" x1="0%" y1="0%" x2="100%" y2="100%">
                      <stop offset="0%" stop-color="#4facfe" />
                      <stop offset="100%" stop-color="#00f2fe" />
                    </linearGradient>
                  </defs>
                  
                  <!-- 主体 -->
                  <rect x="30" y="20" width="40" height="60" rx="10" ry="10" fill="url(#robot-chat-float)" />
                  
                  <!-- 天线 -->
                  <line x1="40" y1="20" x2="40" y2="10" stroke="#4facfe" stroke-width="2" />
                  <circle cx="40" cy="10" r="3" fill="#00f2fe" />
                  <line x1="60" y1="20" x2="60" y2="10" stroke="#4facfe" stroke-width="2" />
                  <circle cx="60" cy="10" r="3" fill="#00f2fe" />
                  
                  <!-- 眼睛 -->
                  <circle cx="40" cy="40" r="7" fill="#ffffff" />
                  <circle cx="60" cy="40" r="7" fill="#ffffff" />
                  <circle cx="40" cy="40" r="3.5" fill="#0f172a" />
                  <circle cx="60" cy="40" r="3.5" fill="#0f172a" />
                  <circle cx="38.5" cy="38.5" r="1.5" fill="white" />
                  <circle cx="58.5" cy="38.5" r="1.5" fill="white" />
                  
                  <!-- 嘴巴 -->
                  <rect x="40" y="55" width="20" height="5" rx="2.5" ry="2.5" fill="#ffffff" />
                  
                  <!-- 耳朵/侧部装饰 -->
                  <rect x="25" y="35" width="5" height="15" rx="2.5" ry="2.5" fill="url(#robot-chat-float)" />
                  <rect x="70" y="35" width="5" height="15" rx="2.5" ry="2.5" fill="url(#robot-chat-float)" />
                </svg>
              </span>
            </div>
            <div class="message-content">
              <div class="message-text" v-html="formatMessage(msg.content)"></div>
            </div>
          </div>
        </template>
        
        <!-- AI思考中状态 -->
        <div v-if="isLoading" class="message assistant-message thinking-message">
          <div class="message-avatar ai-thinking-avatar">
            <svg viewBox="0 0 100 100" width="30" height="30" xmlns="http://www.w3.org/2000/svg">
              <!-- 机器人头部 - 思考中的样式 -->
              <defs>
                <linearGradient id="robot-thinking-float" x1="0%" y1="0%" x2="100%" y2="100%">
                  <stop offset="0%" stop-color="#4facfe">
                    <animate attributeName="stop-color" values="#4facfe;#00f2fe;#4facfe" dur="3s" repeatCount="indefinite" />
                  </stop>
                  <stop offset="100%" stop-color="#00f2fe">
                    <animate attributeName="stop-color" values="#00f2fe;#4facfe;#00f2fe" dur="3s" repeatCount="indefinite" />
                  </stop>
                </linearGradient>
              </defs>
              
              <!-- 主体 -->
              <rect x="30" y="20" width="40" height="60" rx="10" ry="10" fill="url(#robot-thinking-float)" />
              
              <!-- 天线 -->
              <line x1="40" y1="20" x2="40" y2="10" stroke="#4facfe" stroke-width="2" />
              <circle cx="40" cy="10" r="3" fill="#00f2fe" />
              <line x1="60" y1="20" x2="60" y2="10" stroke="#4facfe" stroke-width="2" />
              <circle cx="60" cy="10" r="3" fill="#00f2fe" />
              
              <!-- 眼睛 - 思考状态 -->
              <circle cx="40" cy="40" r="7" fill="#ffffff" />
              <circle cx="60" cy="40" r="7" fill="#ffffff" />
              
              <!-- 眼睛动画 - 转动的思考 -->
              <circle cx="40" cy="40" r="3.5" fill="#0f172a">
                <animateTransform attributeName="transform" type="rotate" from="0 40 40" to="360 40 40" dur="3s" repeatCount="indefinite" />
              </circle>
              <circle cx="60" cy="40" r="3.5" fill="#0f172a">
                <animateTransform attributeName="transform" type="rotate" from="0 60 40" to="360 60 40" dur="3s" repeatCount="indefinite" />
              </circle>
              
              <!-- 嘴巴 - 思考状态 -->
              <rect x="40" y="55" width="20" height="5" rx="2.5" ry="2.5" fill="#ffffff">
                <animate attributeName="width" values="20;15;20" dur="1.5s" repeatCount="indefinite" />
                <animate attributeName="x" values="40;42.5;40" dur="1.5s" repeatCount="indefinite" />
              </rect>
              
              <!-- 耳朵/侧部装饰 -->
              <rect x="25" y="35" width="5" height="15" rx="2.5" ry="2.5" fill="url(#robot-thinking-float)" />
              <rect x="70" y="35" width="5" height="15" rx="2.5" ry="2.5" fill="url(#robot-thinking-float)" />
              
              <!-- 思考泡泡 -->
              <circle cx="70" cy="25" r="3" fill="#ffffff" opacity="0.8">
                <animate attributeName="cy" values="25;20;25" dur="2s" repeatCount="indefinite" />
              </circle>
              <circle cx="78" cy="20" r="2" fill="#ffffff" opacity="0.6">
                <animate attributeName="cy" values="20;15;20" dur="2.5s" repeatCount="indefinite" />
              </circle>
            </svg>
          </div>
          <div class="message-content thinking-content">
            <div class="thinking-header">
              <div class="thinking-title">AI深度思考中...</div>
            </div>
            
            <div class="thinking-process">
              <div class="thinking-step" :class="{ active: activeThinkingStep === 0 }">
                <div class="step-icon">📊</div>
                <div class="step-text">分析问题</div>
              </div>
              <div class="thinking-step" :class="{ active: activeThinkingStep === 1 }">
                <div class="step-icon">🔍</div>
                <div class="step-text">检索知识</div>
              </div>
              <div class="thinking-step" :class="{ active: activeThinkingStep === 2 }">
                <div class="step-icon">💡</div>
                <div class="step-text">生成解答</div>
              </div>
            </div>
            
            <div class="thinking-animation">
              <div class="thinking-dot"></div>
              <div class="thinking-dot"></div>
              <div class="thinking-dot"></div>
              <div class="thinking-dot"></div>
              <div class="thinking-dot"></div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="chat-input">
        <el-input 
          v-model="userQuestion" 
          placeholder="请输入您的金融问题..." 
          :disabled="isLoading || !isUserLoggedIn"
          @keydown.enter.prevent="sendQuestion"
        />
        <el-button 
          type="primary" 
          :loading="isLoading"
          :disabled="!userQuestion.trim() || !isUserLoggedIn"
          @click="sendQuestion"
        >发送</el-button>
      </div>
      
      <!-- 未登录提示 -->
      <div v-if="!isUserLoggedIn" class="login-notice">
        <p>请先登录后使用AI问答功能</p>
        <el-button type="primary" size="small" @click="goToLogin">去登录</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick, computed, watch } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';

const router = useRouter();
const messagesRef = ref(null);
const isChatOpen = ref(false);
const userQuestion = ref('');
const chatHistory = ref([]);
const isLoading = ref(false);
const user = ref(null);
const isUserLoggedIn = computed(() => user.value !== null);
const activeThinkingStep = ref(0);
const thinkingStepInterval = ref(null);

onMounted(() => {
  // 从localStorage读取用户信息
  const userStr = localStorage.getItem('user');
  if (userStr) {
    user.value = JSON.parse(userStr);
  }
});

onBeforeUnmount(() => {
  if (thinkingStepInterval.value) {
    clearInterval(thinkingStepInterval.value);
  }
});

function toggleChat() {
  isChatOpen.value = !isChatOpen.value;
  
  if (isChatOpen.value) {
    // 聊天窗口打开后，滚动到底部
    nextTick(() => {
      scrollToBottom();
    });
  }
}

// 发送问题
async function sendQuestion() {
  if (!userQuestion.value.trim() || isLoading.value || !isUserLoggedIn.value) return;
  
  // 添加用户问题到聊天历史
  const question = userQuestion.value.trim();
  chatHistory.value.push({
    role: 'user',
    content: question
  });
  
  userQuestion.value = ''; // 清空输入框
  isLoading.value = true;
  
  // 滚动到底部
  await scrollToBottom();
  
  // 启动思考步骤动画
  startThinkingStepAnimation();
  
  // 准备历史对话记录（最近5轮）
  const recentMessages = [];
  for (let i = Math.max(0, chatHistory.value.length - 10); i < chatHistory.value.length - 1; i++) {
    if (chatHistory.value[i]) {
      recentMessages.push({
        role: chatHistory.value[i].role,
        content: chatHistory.value[i].content
      });
    }
  }
  
  try {
    // 调用API获取回答
    const response = await axios.post('http://localhost:5000/api/chat', {
      user_id: user.value.id,
      question: question,
      history: recentMessages
    });
    
    if (response.data.code === 0) {
      // 添加AI回答
      chatHistory.value.push({
        role: 'assistant',
        content: response.data.data.answer
      });
    } else {
      // 显示错误信息
      let errorMsg = response.data.msg;
      
      // 检测特定错误类型
      if (errorMsg.includes('401') && errorMsg.includes('令牌')) {
        errorMsg = "API密钥已过期或无效。请联系管理员更新智谱AI API密钥。";
      }
      
      chatHistory.value.push({
        role: 'assistant',
        content: `抱歉，出现了问题：${errorMsg}`
      });
    }
  } catch (error) {
    console.error('聊天请求错误:', error);
    
    // 提供更友好的错误信息
    let errorMsg = error.message;
    
    // 检查是否为连接错误
    if (error.message.includes('Network Error') || error.code === 'ECONNREFUSED') {
      errorMsg = "无法连接到后端服务。请确保后端服务器正在运行。";
    }
    
    chatHistory.value.push({
      role: 'assistant',
      content: `抱歉，服务暂时不可用：${errorMsg}`
    });
  } finally {
    // 停止思考步骤动画
    stopThinkingStepAnimation();
    isLoading.value = false;
    await scrollToBottom();
  }
}

// 启动思考步骤动画
function startThinkingStepAnimation() {
  // 重置到第一步
  activeThinkingStep.value = 0;
  
  // 清除之前的定时器（如果存在）
  if (thinkingStepInterval.value) {
    clearInterval(thinkingStepInterval.value);
  }
  
  // 设置步骤切换的定时器，每2秒切换到下一步
  thinkingStepInterval.value = setInterval(() => {
    activeThinkingStep.value = (activeThinkingStep.value + 1) % 3;
  }, 2000);
}

// 停止思考步骤动画
function stopThinkingStepAnimation() {
  if (thinkingStepInterval.value) {
    clearInterval(thinkingStepInterval.value);
    thinkingStepInterval.value = null;
  }
}

// 格式化消息内容，简单处理换行和空格
function formatMessage(content) {
  // 简单替换换行为<br>标签，空格为&nbsp;
  return content
    .replace(/\n/g, '<br>')
    .replace(/  /g, '&nbsp;&nbsp;');
}

// 滚动到底部
async function scrollToBottom() {
  await nextTick();
  if (messagesRef.value) {
    messagesRef.value.scrollTop = messagesRef.value.scrollHeight;
  }
}

// 跳转到登录页
function goToLogin() {
  router.push('/login');
  isChatOpen.value = false; // 关闭聊天窗口
}

// 监听聊天历史变化，自动滚动到底部
watch(chatHistory, () => {
  scrollToBottom();
});
</script>

<style scoped>
.ai-chat-float {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.chat-toggle {
  display: flex;
  align-items: center;
  background: linear-gradient(to right, #4facfe, #00f2fe);
  padding: 10px 15px;
  border-radius: 30px;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  color: white;
  transition: all 0.3s ease;
}

.chat-toggle:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
}

.chat-icon {
  font-size: 24px;
  margin-right: 8px;
}

.chat-expanded .chat-icon {
  margin-right: 0;
}

.chat-label {
  font-weight: 600;
  transition: all 0.3s ease;
}

.chat-window {
  margin-bottom: 15px;
  width: 350px;
  height: 500px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  animation: slideIn 0.3s ease-out;
}

@keyframes slideIn {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

.chat-header {
  padding: 15px;
  background: linear-gradient(to right, #4facfe, #00f2fe);
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-header h3 {
  margin: 0;
  font-size: 16px;
}

.close-btn {
  cursor: pointer;
  font-size: 22px;
  line-height: 1;
}

.chat-messages {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
}

.welcome-message {
  text-align: center;
  padding: 20px;
}

.welcome-icon {
  font-size: 36px;
  margin-bottom: 10px;
}

.welcome-message h4 {
  margin: 0 0 10px;
}

.welcome-message p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.message {
  display: flex;
  margin-bottom: 15px;
}

.user-message {
  justify-content: flex-end;
}

.message-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
}

.user-message .message-avatar {
  order: 2;
  margin-right: 0;
  margin-left: 8px;
  background-color: #4f46e5;
  color: white;
}

.assistant-message .message-avatar {
  background-color: #0ea5e9;
  color: white;
}

.message-content {
  max-width: 70%;
  padding: 10px;
  border-radius: 12px;
  word-break: break-word;
}

.user-message .message-content {
  background-color: #eff6ff;
  color: #1e3a8a;
  border-top-right-radius: 0;
}

.assistant-message .message-content {
  background-color: #f8fafc;
  color: #0f172a;
  border-top-left-radius: 0;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.ai-thinking-avatar {
  background: linear-gradient(135deg, #0ea5e9, #3b82f6) !important;
  animation: pulse 2s infinite;
}

.thinking-content {
  background: linear-gradient(135deg, #ebf8ff, #e6f7ff, #f0f9ff) !important;
  border: 1px solid rgba(14, 165, 233, 0.2);
}

.thinking-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.thinking-title {
  font-weight: 600;
  color: #0369a1;
}

.thinking-process {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.thinking-step {
  display: flex;
  flex-direction: column;
  align-items: center;
  opacity: 0.6;
}

.thinking-step.active {
  opacity: 1;
}

.step-icon {
  font-size: 16px;
  background: white;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 5px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.step-text {
  font-size: 12px;
  color: #0c4a6e;
  text-align: center;
}

.thinking-animation {
  display: flex;
  align-items: center;
  gap: 4px;
  justify-content: center;
  height: 10px;
  margin-top: 10px;
}

.thinking-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: linear-gradient(to bottom, #0ea5e9, #0284c7);
  opacity: 0.8;
  animation: wave 1.5s infinite ease-in-out;
}

.thinking-dot:nth-child(1) { animation-delay: 0s; }
.thinking-dot:nth-child(2) { animation-delay: 0.2s; }
.thinking-dot:nth-child(3) { animation-delay: 0.4s; }
.thinking-dot:nth-child(4) { animation-delay: 0.6s; }
.thinking-dot:nth-child(5) { animation-delay: 0.8s; }

@keyframes wave {
  0%, 40%, 100% { transform: translateY(0); }
  20% { transform: translateY(-4px); }
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

.chat-input {
  padding: 10px;
  display: flex;
  border-top: 1px solid #e2e8f0;
}

.chat-input .el-input {
  margin-right: 8px;
}

.login-notice {
  padding: 10px;
  background-color: #f8fafc;
  text-align: center;
  font-size: 14px;
  color: #64748b;
}

.login-notice p {
  margin: 0 0 8px;
}
</style>
